package v1

import (
	"errors"
	"gin-luban-server/global"
	"gin-luban-server/model/response"
	"gin-luban-server/service"
	"github.com/gin-gonic/gin"
	"github.com/gorilla/websocket"
	"go.uber.org/zap"
	"net/http"
	"strconv"
)

var upGrader = websocket.Upgrader{
	ReadBufferSize:  10240,
	WriteBufferSize: 1024 * 1024 ,
	CheckOrigin: func(r *http.Request) bool {
		return true
	},
}

func AnsibleHostInitWs(c *gin.Context){
	id  := c.DefaultQuery("Id", "")
	uuid := c.DefaultQuery("uuid", "")
	if   id == "" || uuid== "" {
		err :=errors.New("参数为空")
		global.GVA_LOG.Error("连接失败!", zap.Any("err", err))
		response.FailWithMessage("连接失败" + err.Error(), c)
	}
	ids, _ := strconv.Atoi(id)

	isAdmin :=service.CheckUserToken(uuid)
	if !isAdmin {
		err :=errors.New("用户认证失败")
		global.GVA_LOG.Error("用户认证失败!", zap.Any("err", err))
		response.FailWithMessage("用户认证失败" + err.Error(), c)
	}
	cols :=uint32(70)
	rows :=uint32(24)
	ws, err := upGrader.Upgrade(c.Writer, c.Request, nil)
	if err != nil {
		response.FailWithMessage("连接失败！" + err.Error(), c)
		ws.Close()
	}
	client, channel, err := service.NewAnsibleClient(cols,rows,uint(ids))
	if err != nil {
		//response.FailWithMessage("初始化失败！" + err.Error(), c)
		client.Close()
		channel.Close()
		ws.Close()
	}
	command := "sudo mv /home/appuser/hosts /etc/ansible/hosts && sudo chown -R root:root /etc/ansible/hosts && sudo ansible-playbook -i /etc/ansible/hosts /etc/ansible/top.yml"
    service.AnsibleWebSocketHandler(ws,client,channel,isAdmin,ids,command)
}